import os
from pathlib import Path
import uvicorn
from fastapi import FastAPI, File, BackgroundTasks, UploadFile, HTTPException
from starlette.responses import FileResponse
import subprocess

app = FastAPI()

# 临时文件存储目录
base_path = Path("/tmp/convert")
base_path.mkdir(exist_ok=True)

@app.get('/probe')
def index():
    return "OK"

@app.post("/translate/doc")
async def translate_doc(
    file: UploadFile = File(...),
    background_tasks: BackgroundTasks = None
):
    print(f"translate_doc filename : {file.filename}")
    # 获取文件file名称
    output_name = file.filename if file.filename else "test.doc"
    # 文件全路径，包含output_name
    full_path = os.path.join(base_path, output_name)
    print(f"translate_doc full_path : {full_path}")
    # 将文件保存到本地
    with open(full_path, "wb") as f:
        content = await file.read()
        f.write(content)
    print(f"translate_doc write finish ... ")
    # 读取本地 output_file_name
    # 调用 LibreOffice 进行转换
    result = subprocess.run([
        'libreoffice',
        '--headless',
        '--convert-to', 'docx',
        '--outdir', str(base_path),
        str(full_path)
    ], capture_output=True, text=True, timeout=60)  # 设置超时
    # 检查转换是否成功
    if result.returncode != 0:
        error_msg = result.stderr if result.stderr else result.stdout
        raise HTTPException(status_code=500, detail=f"Conversion failed: {error_msg}")
    print(f"translate_doc translate finish {full_path}x")
    # 删除文件
    background_tasks.add_task(os.remove, full_path)
    background_tasks.add_task(os.remove, f"{full_path}x")
    # 推送数据
    print(f"translate_doc target {full_path}x")
    return FileResponse(
        path=f"{full_path}x",
        filename=f"{output_name}x",
        media_type='application/octet-stream'
    )


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
